<template>
  <!-- 服务端 -->
  <div style="height: 100%; width: 100%" :class="{ active: activeWinBsr }">
    <div
      class="modal"
      @click="activeWinBsr = !activeWinBsr"
      :class="{ active: activeWinBsr }"
    ></div>

    <JwChat-index
      style="height: 100%; width: 100%"
      :config="config"
      :showRightBox="false"
      :scrollType="'scroll'"
      :taleList="taleList"
      @enter="bindEnter"
      v-model="inputMsg"
      :toolConfig="tool"
      :winBarConfig="winBarConfig"
    >
      <template slot="header">
        <div style="margin-left: 20px; font-size: 14px" class="user">
          用户id:<span style="font-size: 16px; font-weight: bold">{{
            winBarConfig.active
          }}</span>
        </div>
        <span @click="showWinBar">会话列表</span>
      </template>
      <template slot="tools">
        <input
          @change="referenceUpload"
          type="file"
          id="common_chat_opr_fileUpload2"
          style="display: none"
        />
      </template>
    </JwChat-index>
  </div>
</template>

<script>
import { uploadImg } from "@/utils/uploadImg";
import axios from "axios";
import moment from "moment";
export default {
  data() {
    return {
      activeWinBsr: false,
      allList: {},
      fromId: "244885381783080960",
      inputMsg: "",
      taleList: [],
      tool: {
        show: ["img", ["文件1", "", "美图"]],
        // showEmoji: false,
        callback: this.toolEvent,
      },
      config: {
        img: "../image/cover.png",
        name: "服务台",
        dept: "",
        callback: this.bindCover,
        historyConfig: {
          show: false,
          tip: "加载更多",
          callback: this.bindLoadHistory,
        },
      },
      winBarConfig: {
        active: "",
        width: "260px",
        listHeight: "60px",
        list: [
          // {
          //   id: "win00",
          //   img: "..//image/cover.png",
          //   name: "JwChat",
          //   dept: "最简单、最便捷",
          //   readNum: 99,
          // },
          // {
          //   id: "win01",
          //   img: "..//image/three.jpeg",
          //   name: "阳光明媚爱万物",
          //   dept: "沙拉黑油",
          //   readNum: 12,
          // },
          // {
          //   id: "win02",
          //   img: "..//image/two.jpeg",
          //   name: "只盼流星不盼雨",
          //   dept: "最后说的话",
          // },
          // {
          //   id: "win03",
          //   img: "..//image/one.jpeg",
          //   name: "留恋人间不羡仙",
          //   dept: "这里可以放万物",
          // },
          // {
          //   id: "win04",
          //   img: "..//image/three.jpeg",
          //   name: "阳光明媚爱万物",
          //   dept: "官方客服",
          // },
        ],
        callback: this.bindWinBar,
      },
    };
  },
  computed: {
    toId: {
      get() {
        return this.winBarConfig.active;
      },
      set(newVal) {
        this.winBarConfig.active = newVal;
      },
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    showWinBar() {
      this.activeWinBsr = true;
    },
    setWinBarConfig(data) {
      // from 取to
      if (data.from == this.fromId) {
        if (!this.winBarConfig.active) {
          this.winBarConfig.active = data.to;
          this.getHistory();
        }
        if (!this.allList[data.to]) {
          this.allList[data.to] = {
            id: data.to,
            date: data.date,
            img: require("@/assets/user.png"),
            name: "用户" + data.to,
            dept: "",
            readNum: this.winBarConfig.active === data.to ? 0 : 1,
          };
        } else {
          if (this.winBarConfig.active == data.to) {
            console.log(1);
          } else {
            this.allList[data.to].readNum++;
            this.allList[data.to].date = data.date;
          }

          // this.winBarConfig.active == data.to
          //   : ;
          // let _index = this.winBarConfig.list.findIndex((item) => {
          //   return item.id == data.to;
          // });
          // let list = this.winBarConfig.list;
          // let c = list.splice(_index, 1);
          // list.push(c[0]);
          // this.winBarConfig.list = list;
        }
      } else {
        if (!this.winBarConfig.active) {
          this.winBarConfig.active = data.from;
        }
        // 取from
        if (!this.allList[data.from]) {
          this.allList[data.from] = {
            id: data.from,
            date: data.date,
            img: require("@/assets/user.png"),
            name: "用户" + data.from,
            dept: "",
            readNum: this.winBarConfig.active === data.from ? 0 : 1,
          };
        } else {
          if (this.toId == data.from) {
            console.log(1);
          } else {
            debugger;
            this.allList[data.from].readNum++;
            this.allList[data.from].date = data.date;
          }

          // :
        }
      }

      this.winBarConfig.list = Object.values(this.allList).sort((a, b) => {
        // return moment(a.date)- moment(b.date)
        debugger;
        return b.date < a.date ? -1 : 1;
      });
    },
    referenceUpload(e) {
      // 2.文件上传
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
      formData.append("fileType", "images");
      uploadImg(formData).then(({ data }) => {
        let img = data.data;
        const msgObj = {
          date: moment().format("YYYY-MM-DD HH:mm:ss"),
          text: { text: "<img data-src='" + img + "'/>" },
          mine: true,
          name: "客服",
          img: require("@/assets/service.png"),
        };

        // 发送的数据
        const postData = {
          to: this.toId,
          from: this.fromId,
          text: img,
          type: "1",
        };
        this.WS.send(postData);
        this.taleList.push(msgObj);
        document.getElementById("common_chat_opr_fileUpload2").value = "";
      });
    },
    init() {
      console.log(this.$route.query.id);
      this.WS = new this.$WSocket({
        url: `ws://116.62.168.208:8183/webSocket/${this.fromId}/457881/server`,
        // 心跳时间（单位:ms）
        // 'heartBeat':5000,
        // 发送心跳信息（支持json传入）(这个一般内容不重要，除非后端变态)
        // 'heartMsg':'hello',
        // 开起重连
        reconnect: false,
        // 重连间隔时间（单位:ms）
        // 'reconnectTime':5000,
        // 重连次数
        // 'reconnectTimes':10
      });
      this.WS.onerror((e) => {
        console.log(e, "链接失败");
      });
      this.WS.onmessage((data) => {
        const d = JSON.parse(data);
        if (d.from && d.to) {
          // this.fromId = d.from;
          // this.toId = d.to;
          this.setWinBarConfig(d);
        }
        this.updateList(JSON.parse(data));
      });
      this.WS.onopen((e) => {
        console.log(e);
      });
    },
    updateList(data) {
      if (this.toId !== data.from) {
        return;
      }
      if (data.type == 1) {
        this.taleList.push({
          date: data.date,
          text: { text: "<img data-src='" + data.text + "'/>" },
          mine: false,
          name: "用户" + data.from,
          img: require("@/assets/user.png"),
        });
      } else {
        this.taleList.push({
          date: data.date,
          text: { text: data.text },
          mine: false,
          name: "客服",
          img: require("@/assets/user.png"),
        });
      }
    },

    bindEnter() {
      const msg = this.inputMsg;
      if (!msg) return;
      const msgObj = {
        date: moment().format("YYYY-MM-DD HH:mm:ss"),
        text: { text: msg },
        mine: true,
        name: "客服",
        img: require("@/assets/service.png"),
      };
      const postData = {
        to: this.toId,
        from: this.fromId,
        text: msg,
        name: "名字",
        type: "0",
      };
      this.WS.send(postData);
      this.taleList.push(msgObj);
    },
    /**
     * @description:
     * @param {*} type 当前点击的按钮
     * @param {*} plyload 附加文件或者需要处理的数据
     * @return {*}
     */
    toolEvent(type, plyload) {
      console.log("tools", type, plyload);
      document.querySelector("#common_chat_opr_fileUpload2").click();
    },
    /**
     * @description: 点击加载更多的回调函数
     * @param {*}
     * @return {*}
     */
    bindLoadHistory() {
      const history = new Array(3).fill().map((i, j) => {
        return {
          date: "2020/05/20 23:19:07",
          text: { text: j + new Date() },
          mine: false,
          name: "JwChat",
          img: "image/three.jpeg",
        };
      });
      let list = history.concat(this.taleList);
      this.taleList = list;
      console.log("加载历史", list, history);
    },
    bindCover(type) {
      console.log("header", type);
    },
    bindWinBar(play = {}) {
      const { type, data = {} } = play;
      console.log(data);
      if (type === "winBar") {
        const { id, dept, name, img } = data;
        if (this.toId == id) {
          return false;
        }
        console.log(dept, name, img);
        this.winBarConfig.active = id;
        // 重新获取聊天几率应该
        let _index = this.winBarConfig.list.findIndex((item) => {
          return item.id == id;
        });
        console.log(_index);
        this.winBarConfig.list[_index].readNum = 0;
        this.toId = id;
        this.getHistory();
      }
    },
    getHistory() {
      axios({
        url: "http://116.62.168.208:8183/chat/list",
        params: {
          pageIndex: 1,
          pageSize: 10000,
          cRecordId: this.winBarConfig.active,
        },
      }).then(({ data }) => {
        if (!data.code) {
          const detail = data.data.detail;
          const conversionData = detail.map((item) => {
            let msgObj = {};
            if (item.cType == 1) {
              // 图片
              msgObj = {
                date: moment(Number(item.cDate)).format("YYYY-MM-DD HH:mm:ss"),
                text: { text: "<img data-src='" + item.cTxt + "'/>" },
                mine: item.cTo != this.fromId,
                name: item.cFrom == this.fromId ? "客服" : "用户" + item.cFrom,
                img:
                  item.cTo != this.fromId
                    ? require("@/assets/service.png")
                    : require("@/assets/user.png"),
              };
            } else {
              msgObj = {
                date: moment(Number(item.cDate)).format("YYYY-MM-DD HH:mm:ss"),
                text: { text: item.cTxt },
                mine: item.cTo != this.fromId,
                name: item.cFrom == this.fromId ? "客服" : "用户" + item.cFrom,
                img:
                  item.cTo !== this.fromId
                    ? require("@/assets/service.png")
                    : require("@/assets/user.png"),
              };
            }

            return msgObj;
          });
          console.log(conversionData);
          // let list = conversionData.concat(this.taleList);
          if (!this.first) {
            this.first = true;
            let list = conversionData.concat(this.taleList);
            this.taleList = list;
          } else {
            this.taleList = conversionData;
          }
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.active {
  /deep/.ChatPage .winBar {
    transform: translateX(0%);
    display: block;
    z-index: 999;
  }
}
.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: none;
  &.active {
    display: block;
  }
}
/deep/.ChatPage .winBar {
  transform: translateX(0%);
  top: 0;
  left: 0;
  z-index: 999;
  display: none;
}
/deep/ .chat-content {
  height: 100%;
}
/deep/.chatBox {
  flex: 1;
}
/deep/.chatPage {
  width: 100% !important;
  height: 100% !important;
}
/deep/.wrapper {
  width: 100% !important;
  height: 100% !important;
}
</style>
